package cn.edu.sdjzu.xg.eagle.service.impl;

import cn.edu.sdjzu.xg.eagle.dao.UserDao;
import cn.edu.sdjzu.xg.eagle.entity.User;
import cn.edu.sdjzu.xg.eagle.exception.BaseException;
import cn.edu.sdjzu.xg.eagle.factory.DaoFactory;
import cn.edu.sdjzu.xg.eagle.service.UserService;
import cn.edu.sdjzu.xg.eagle.util.JdbcHelper;

import java.lang.reflect.InvocationTargetException;
import java.sql.Connection;
import java.sql.SQLException;

public final class UserServiceImpl implements UserService {
    //DaoFactory.getDao方法声明了BaseException，但后者扩展了RuntimeException，
    //调用者不再强制处理
    private UserDao userDao =
            DaoFactory.getDao(UserDao.class, "UserDaoImpl");
    @Override
    public void login(User userToLogin) throws SQLException{
        Connection connection = JdbcHelper.getConn();
        userDao.login(connection, userToLogin);
        JdbcHelper.close(connection);
    }


    @Override
    public User find(Integer id) throws SQLException, BaseException, InvocationTargetException {
        Connection connection = JdbcHelper.getConn();
//        User actor = actorDao.find(connection, id);
        User user = userDao.find(connection, id);
        JdbcHelper.close(connection);
        return user;
    }
    @Override
    public boolean delete( Long id) throws SQLException {
        return false;
    }
//    @Override
//    public User find(Integer id) throws SQLException, BaseException {
//        Connection connection = JdbcHelper.getConn();
//        User actor = actorDao.find(connection, id);
//        User user = userDao.find(connection, id);
//        JdbcHelper.close(connection);
//        return user;
//    }


    //这里修改user, 是不是就不用返回了，调用者使用引用
    @Override
    public int add(User user)throws SQLException {
        Connection connection = JdbcHelper.getConn();
        int id = userDao.add(connection, user);
        JdbcHelper.close(connection);
        return id;
    }

    /**
     * 用于被其它Service调用
     * @param connection 其它Service获得的数据库连接
     * @param user
     * @return
     * @throws SQLException
     */

    @Override
    public int add(Connection connection, User user)throws SQLException {
        int id = userDao.add(connection, user);
        return id;
    }


    public boolean update(Connection connection, User user)throws SQLException {
        boolean updated = userDao.update(connection, user);
        return updated;
    }
    public boolean update(User user)throws SQLException {
        Connection connection = JdbcHelper.getConn();
        boolean updated = userDao.update(connection, user);
        JdbcHelper.close(connection);
        return updated;
    }
//    public Actor login(User userToLogin) throws SQLException {
//        Connection connection = JdbcHelper.getConn();
//        Actor actor = userDao.login(connection, userToLogin);
//        JdbcHelper.close(connection);
//        return actor;
//    }


}
